package cn.wx.scholar.neo4j.service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;

import cn.wx.common.persistence.exception.MyException;
import cn.wx.common.persistence.web.ResponseCode;
import cn.wx.scholar.core.entity.ScholarBook;
import cn.wx.scholar.core.entity.qo.ScholarBookQ;
import cn.wx.scholar.core.service.ScholarBookService;
import cn.wx.scholar.neo4j.entity.Neo4jBook;
import cn.wx.scholar.neo4j.entity.qo.Neo4jBookQ;
import cn.wx.scholar.neo4j.repository.BookRepository;

@Service
public class Neo4jBookService {
	
	Logger logger = LoggerFactory.getLogger(Neo4jBookService.class);
	
	@Autowired
	private BookRepository bookRepository;
	
	@Autowired
	private ScholarBookService scholarBookService;
	
	public Page<Neo4jBook> findAllBooksByExpertId(Neo4jBookQ neo4jBookQ) {
		
		/**
		 * 必要参数
		 */
		if(neo4jBookQ == null || neo4jBookQ.getExpertId() == null) {
			throw new MyException(ResponseCode.PARAMETER_REQUIRED);
		}
		
		Page<Neo4jBook> pages = bookRepository.findAllBooksByExpertId(neo4jBookQ.getExpertId(), 
			PageRequest.of(neo4jBookQ.getPageSkip(), neo4jBookQ.getPageSize()));
		
    	if(pages!=null && pages.getContent()!=null) {
			
			List<Long> fIds = new ArrayList<>();
			
			for(Neo4jBook mpr : pages) {
				fIds.add(mpr.getfId());
			}
			
			if(fIds.size() > 0) {
				ScholarBookQ nQ = new ScholarBookQ();
				nQ.setfIds(fIds);
				
				List<ScholarBook> books = scholarBookService.queryList(nQ);
				
				
				Map<Long,ScholarBook> cPaperMap = null;
				
				if(books != null && books.size() > 0) {
					cPaperMap = new HashMap<>();
					for(ScholarBook n : books) {
						cPaperMap.put(n.getfId(), n);
					}
				}
				
				if(cPaperMap != null) {
					for(Neo4jBook ew_ : pages.getContent()) {
						covetMysqlToNeo4j(ew_, cPaperMap.get(ew_.getfId()),false);
					}
				}
				
			}
    	}
		
		return pages;
	}
	
	/**
	 * 把mysql 的数据放到 neo4j中 
	 */
	private void covetMysqlToNeo4j(Neo4jBook nO,ScholarBook mO,Boolean isDetails) {
		
		
		if(mO == null) {
			logger.info("this data have no mysqlRecond :"+ nO.getfId());
			return;
		}
		nO.setBookName(mO.getBookName());
		nO.setBookSubtitle(mO.getBookSubtitle());
		nO.setAuthors(mO.getAuthors());
		nO.setPublisher(mO.getPublisher());
	}
	
}
